import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Typography, Input, Table, Tag } from 'antd';
import { Button, Space } from 'antd';
import Highlighter from 'react-highlight-words';
import { SearchOutlined, UndoOutlined } from '@ant-design/icons';
import { connect } from 'dva';
import styles from './index.less';
import './config';

const { Search } = Input;
const { Column } = Table;
var time;

const CodePreview = ({ children }) => (
  <pre className={styles.pre}>
    <code>
      <Typography.Text copyable>{children}</Typography.Text>
    </code>
  </pre>
);

const Warning = (props) => {
  const interval = 6000;
  const { dispatch, warninglist, loading } = props;
  const [searchText, setText] = useState();
  const [searchedColumn, setColumn] = useState();
  const [length, setlen] = useState(0);
  const getColumnSearchProps = (dataIndex, title) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div style={{ padding: 8 }}>
        <Input
          // ref={node => {
          //   this.input = node
          // }}
          placeholder={`查找 ${title}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ marginBottom: 8, display: 'block' }}
        />
        <Space style={{ width: '100%' }}>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 95 }}
          >
            筛选
          </Button>
          <Button
            onClick={() => handleReset(clearFilters)}
            icon={<UndoOutlined />}
            size="small"
            style={{ width: 95, marginLeft: 9 }}
          >
            重置
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase())
        : '',
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (
        text
      ),
  });
  const columns = [
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      width: '5%',
      render: (tags) => (
        <>
          {tags.map((tag) => (
            <Tag color="#cd201f" key={tag}>
              {tag}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '时间',
      dataIndex: 'createTime',
      key: 'alarmId',
      width: '20%',
      ...getColumnSearchProps('createTime', '时间'),
    },
    {
      title: '异常数值(角度/摄氏度/速度)',
      dataIndex: 'numericalValue',
      key: 'alarmId',
      width: '20%',
      ...getColumnSearchProps('numericalValue', '异常数值'),
    },
    {
      title: '车辆编号',
      dataIndex: 'vehicleId',
      key: 'alarmId',
      width: '20%',
      ...getColumnSearchProps('vehicleId', '车辆编号'),
    },
    {
      title: '报警原因',
      dataIndex: 'alarmReason',
      key: 'alarmId',
      ...getColumnSearchProps('alarmReason', '报警原因'),
    },
  ];
  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setText(selectedKeys[0]);
    setColumn(dataIndex);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setText('');
  };

  useEffect(() => {
    dispatch({
      type: 'warnings/getwarning',
      payload: { id: null },
    });
    time = setInterval(() => {
      dispatch({
        type: 'warnings/getwarning',
        payload: { id: null },
      });
    }, interval);

    return () => {
      clearInterval(time);
      localStorage.removeItem('warnIndex');
    };
  }, []);
  const onSearch = (value) => {
    console.log(value);
    if (time) {
      clearInterval(time);
    }
    time = setInterval(() => {
      dispatch({
        type: 'warnings/getwarning',
        payload: { id: value },
      });
    }, interval);
  };
  const download = (value) => {
    const w = window.open('about:blank');
    w.location.href = global.constants.url + '/alarm/export?vehicleId=' + value;
  };
  return (
    <PageContainer>
      <Search
        placeholder="输入车辆id"
        enterButton="数据导出"
        size="large"
        style={{ width: '20%', float: 'right', marginBottom: '10px' }}
        onSearch={download}
      />
      <Search
        placeholder="输入车辆id"
        enterButton="查询"
        size="large"
        style={{ width: '79%', float: 'left', marginBottom: '10px' }}
        onSearch={onSearch}
      />

      <Table
        style={{
          marginTop: '10px',
        }}
        dataSource={warninglist.map((item, index) => {
          if (localStorage.getItem('warnIndex')) {
            if (item.createTime > localStorage.getItem('warnIndex')) {
              item.tags.push('new');
            }
            // if (index === warninglist.length - 1) {
            //   localStorage.setItem('warnIndex', item.createTime);
            // }
          }
          if (index === 0 && !localStorage.getItem('warnIndex')) {
            localStorage.setItem('warnIndex', item.createTime);
          }
          // if (item.alarmId === warninglist.length) {
          //   item.tags = ['new'];
          // }
          if (
            item.alarmReason === '车辆过于倾斜' &&
            item.numericalValue.toString().indexOf('°') === -1
          ) {
            item.numericalValue = item.numericalValue + ' °';
          }
          if (
            item.alarmReason === '车速过快' &&
            item.numericalValue.toString().indexOf('km/h') === -1
          ) {
            item.numericalValue = item.numericalValue + ' km/h';
          }
          if (
            item.alarmReason === '发动机温度过高' &&
            item.numericalValue.toString().indexOf('℃') === -1
          ) {
            item.numericalValue = item.numericalValue + ' ℃';
          }
          return item;
        })}
        columns={columns}
      />
    </PageContainer>
  );
};

export default connect(({ warnings: { warninglist } }) => ({
  warninglist,
}))(Warning);
